﻿#region Copyright (c) 2012-11, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;


namespace Amarok.Agents
{
	/// <summary>
	/// This type represents an Operation Message. Operation Messages are a special kind of Message intended to 
	/// trigger the execution of operations. That can be either operations for changing state, for example starting 
	/// a measurement, or operations for querying information, for example querying the list of users.
	/// 
	/// Types derived from this base class should follow a naming convention. An Operation Message intended to change 
	/// state or data should be named after the object that is affected, preceded by a verb that describes how that 
	/// object is affected; for example: StartMeasurement, AddUser, ExitApplication. An Operation Message intended to 
	/// query information should be named after the object which is queried, preceded by the verb Query; for example: 
	/// QueryUsers, QueryMeasurementStatus.
	/// 
	/// As for all Messages, it is good design practice to implement Operation Messages as immutable types so that 
	/// accidental modifications are impossible. This is important since Operation Messages will be transfered to 
	/// other Agents, thus, it is very likely that the content of those Operation Messages will be accessed in other 
	/// threads concurrently.
	/// 
	/// In addition, Operation Messages should contain copies of data (entities) or some kind of unique identifier 
	/// (identities). Latter can then be used to query for that identified entities. Never transfer object references 
	/// to private Agent data, except for global shared data that never changes; always transfer copies of data.
	/// </summary>
	/// 
	/// <typeparam name="TResult">
	/// The type of result value that is returned from the operation.</typeparam>
	/// <typeparam name="TProgress">
	/// The type of progress value that is used to report progress while the operation is running.</typeparam>
	[Serializable]
	public abstract class Operation<TResult, TProgress> : Operation
	{
		// Implementation Notes:
		//
		//	Some fields are marked as non-serialized, because we don't want their state to be transfered
		//	between processes. This causes those fields not being initialized on deserialization, so we have 
		//	to initialize them manually by implementing a custom deserialization callback.

		// data
		[NonSerialized]
		private TaskCompletionSource<TResult> mCompletionTaskSource;
		[NonSerialized]
		private Action<TProgress> mProgressEvent;
		[NonSerialized]
		private Lazy<ActionBlock<TProgress>> mLazyProgressActionBlock;


		#region ++ Public Interface (Completion) ++

		/// <summary>
		/// Gets a task that represents the asynchronously running operation. This task can be used to wait for 
		/// operation completion, to register a continuation and to access state and result of the operation.
		/// </summary>
		public Task<TResult> Completion
		{
			get
			{
				return mCompletionTaskSource.Task;
			}
		}


		/// <summary>
		/// Completes the operation successfully with the supplied result value. The operation result will contain 
		/// the supplied result value. If the operation has been completed before an exception will be thrown.
		/// </summary>
		/// 
		/// <param name="result">
		/// The result value of the successfully completed operation.</param>
		/// 
		/// <exception cref="InvalidOperationException">
		/// The underlying Task is already in one of the final states.</exception>
		public void Complete(TResult result)
		{
			_CompleteProgress();

			mCompletionTaskSource.SetResult(result);
		}

		/// <summary>
		/// Completes the operation as canceled. The operation result will express that the operation was 
		/// canceled. If the operation has been completed before an exception will be thrown.
		/// </summary>
		/// 
		/// <exception cref="InvalidOperationException">
		/// The underlying Task is already in one of the final states.</exception>
		public void CompleteCanceled()
		{
			_CompleteProgress();

			mCompletionTaskSource.SetCanceled();
		}

		/// <summary>
		/// Completes the operation as failed. The operation result will express that the operation has failed 
		/// and contains the supplied exception. If the operation has been completed before an exception will 
		/// be thrown.
		/// </summary>
		/// 
		/// <param name="exception">
		/// The exception that describes the cause of the operation failure.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="InvalidOperationException">
		/// The underlying Task is already in one of the final states.</exception>
		public void CompleteFaulted(Exception exception)
		{
			Verify.NotNull(exception, "exception");

			_CompleteProgress();

			mCompletionTaskSource.SetException(exception);
		}

		#endregion

		#region ++ Public Interface (Progress) ++

		/// <summary>
		/// An event that is raised each time operation progress is reported. The event will be raised in the 
		/// context of an arbitrary thread-pool thread.
		/// </summary>
		public event Action<TProgress> Progress
		{
			add
			{
				mProgressEvent += value;
			}
			remove
			{
				mProgressEvent -= value;
			}
		}


		/// <summary>
		/// Reports the supplied progress value. The progress value indicates the current progress of the running 
		/// operation. This method returns immediately. Registered event handler will be called in the context of 
		/// an arbitrary thread-pool thread, not in the context of the calling thread.
		/// </summary>
		/// 
		/// <param name="progress">
		/// A value indicating the current progress of the running operation.</param>
		public void ReportProgress(TProgress progress)
		{
			var progressActionBlock = mLazyProgressActionBlock.Value;
			progressActionBlock.Post(progress);
		}

		#endregion

		#region ~~ Internal Interface ~~

		/// <summary>
		/// </summary>
		internal override void OnDispose()
		{
			base.OnDispose();

			_CompleteProgress();
		}

		#endregion

		#region ## Protected Interface ##

		/// <summary>
		/// Initializes a new instance.
		/// </summary>
		protected Operation()
		{
			_Initialize();
		}

		#endregion

		#region Implementation

		[OnDeserialized]
		private void _OnDeserialized(StreamingContext context)
		{
			_Initialize();
		}

		private void _Initialize()
		{
			mCompletionTaskSource = new TaskCompletionSource<TResult>();
			mCompletionTaskSource.Task.IgnoreExceptions();

			mLazyProgressActionBlock = new Lazy<ActionBlock<TProgress>>(
				_CreateProgressActionBlock,
				LazyThreadSafetyMode.ExecutionAndPublication);
		}

		private ActionBlock<TProgress> _CreateProgressActionBlock()
		{
			return new ActionBlock<TProgress>(
				new Action<TProgress>(_RaiseProgress),
				new ExecutionDataflowBlockOptions()
				{
					NameFormat = "Operation-Progress-ActionBlock: Id: {1}",
					MaxDegreeOfParallelism = 1,
				});
		}

		private void _RaiseProgress(TProgress progress)
		{
			try
			{
				var handler = mProgressEvent;

				if (handler != null)
					handler(progress);
			}
			catch (Exception)
			{
				// ignore exceptions caused by user-supplied callback
			}
		}

		private void _CompleteProgress()
		{
			// process remaining progress messages
			if (mLazyProgressActionBlock.IsValueCreated)
			{
				mLazyProgressActionBlock.Value.Complete();
				mLazyProgressActionBlock.Value.Completion.Wait();
			}

			// reset event
			mProgressEvent = null;
		}

		#endregion

	}
}
